package com.lqq.controller.restfull;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author lqq
 * @date 2019/1/6
 */
@RestController
@Api(description = "index")
public class IndexController {


    @RequestMapping({"", "/" , "/index"})
    @ApiOperation(value = "index信息",httpMethod = "GET")
    public String index() throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();
        return  "indexMethod: 当前主机ip地址信息：" + address.getHostAddress();
    }


    @RequestMapping({"/login"})
    @ApiOperation(value = "login登录",httpMethod = "GET")
    public String login(HttpServletRequest request,  @RequestParam(defaultValue = "cuihua") String userId) throws UnknownHostException {

        request.getSession().setAttribute("userId", userId);
        InetAddress address = InetAddress.getLocalHost();
        return  "login: 当前主机ip地址信息：" + address.getHostAddress() + "\n"
                +"当前登录用户：" + userId ;
    }

    @RequestMapping({"/logout退出"})
    @ApiOperation(value = "logout",httpMethod = "GET")
    public String logout(HttpServletRequest request) throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();
        HttpSession session = request.getSession();
        String userId =  session.getAttribute("userId").toString();
        session.removeAttribute("userId");
        return  "logout: 当前主机ip地址信息：" + address.getHostAddress()+ "\n"
                + "退出用户：" + userId;
    }

    @RequestMapping({"/hello"})
    @ApiOperation(value = "业务操作",httpMethod = "GET")
    public String hello(HttpServletRequest request) throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();
        HttpSession session = request.getSession();
        Object userId =  session.getAttribute("userId");
        String ret = null;
        if(userId == null){
            ret = "session不存在，不能操作";
        }else {
            ret = "当前用户" + userId + "已经操作业务";
        }
        return  "helloMethod: 当前主机ip地址信息：" + address.getHostAddress() + "\n"
                + ret;
    }


}
